from django.shortcuts import render, redirect, HttpResponse
from django.urls import reverse
from rbac.service.urls import memory_reverse
from rbac import models
from rbac.forms.role import RoleModelForm


def role_list(request):
    """
    角色列表
    :param request:
    :return:
    """
    role_queryset = models.Role.objects.all()

    return render(request, 'rbac/role_list.html', {'data_list': role_queryset})


def role_add(request):
    """
    角色添加
    :param request:
    :return:
    """
    if request.method == 'GET':
        form = RoleModelForm()
        return render(request, 'rbac/change.html', {'form': form})
    form = RoleModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(memory_reverse(request,'rbac:role_list'))
    return render(request, 'rbac/change.html', {'form': form})


def role_change(request, pk):
    """
    角色编辑
    :param request:
    :param pk:
    :return:
    """
    obj = models.Role.objects.filter(id=pk).first()
    if not obj:
        return HttpResponse("数据不存在")

    if request.method == "GET":
        form = RoleModelForm(instance=obj)
        return render(request, 'rbac/change.html', {'form': form})
    form = RoleModelForm(instance=obj, data=request.POST)
    if form.is_valid():
        form.save()
        return redirect(memory_reverse(request, "rbac:role_list"))
    return render(request, 'rbac/change.html', {'form': form})


def role_delete(request, pk):
    """
    删除角色
    :param request:
    :param pk:
    :return:
    """
    obj = models.Role.objects.filter(id=pk).first()
    url = memory_reverse(request, "rbac:role_list")
    if not obj:
        return HttpResponse("删除的数据不存在")
    if request.method == 'GET':
        return render(request, 'rbac/delete.html', {'cancel_url': url})
    obj.delete()
    return redirect(url)
